<script setup lang="tsx">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { EmployeeVO } from '#/api/company/audience/model';
import type { CallLog } from '#/api/contact/task/call/model';

import { computed, onActivated, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { VbenIcon } from '@vben/icons';
import { cloneDeep, getVxePopupContainer } from '@vben/utils';

import {
  Alert,
  Button,
  Card,
  Col,
  message,
  Popconfirm,
  Row,
  Space,
  Spin,
  TabPane,
  Tabs,
} from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { employeeUpdate } from '#/api/company/audience';
import {
  callLogAdd,
  callLogList,
  callTaskAutoRegister,
  callTaskChangeCallStatus,
  callTaskEmployeeNoDesensitizeInfo,
  callTaskInfo,
  callTaskWorkbenchQuery,
} from '#/api/contact/task/call';
import Clink from '#/components/clink/src/btn.vue';
import { useClinkCall } from '#/components/clink/src/useClinkNew';
import { addressCodeMapToArray } from '#/utils/address';
import { getDictOptions } from '#/utils/dict';
import { updateSensitiveSchema } from '#/utils/form';
import RegisterHistoryTable from '#/views/company/audience/components/register-history-table.vue';

import {
  contactHistoryColumns,
  contactResultSchema,
  userSchema,
} from '../workbench';
import sendEmailModal from './send-email-modal.vue';
import sendSmsModal from './send-sms-modal.vue';

defineOptions({
  name: 'ContactPanel',
  inheritAttrs: false,
});

const props = defineProps<{
  audience?: EmployeeVO;
  taskId?: any;
  type: string;
}>();

const emit = defineEmits<{
  (e: 'update:calling', value: boolean): void;
}>();

const { hasAccessByCodes } = useAccess();
const { closeCurrentTab } = useTabs();
const router = useRouter();
const [UserForm, userFormApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 90,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  compact: false,
  schema: userSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
  fieldMappingTime: [
    [
      'addressMap',
      ['countryCode', 'provinceCode', 'cityCode', 'districtCode'],
      null,
    ],
  ],
});

const [ContactResultForm, contactResultFormApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 90,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
      allowClear: true,
    },
  },
  compact: false,
  schema: contactResultSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1',
});

const contactTabKey = ref<string>('1');
const listTabKey = ref<string>('1');

// 预登记
const registerLoading = ref(false);

async function autoRegister() {
  registerLoading.value = true;
  await callTaskAutoRegister(info.value.id);
  info.value.hasRegister = true;
  registerLoading.value = false;
}

// 发短信
const [SendSmsModal, sendSmsModalApi] = useVbenModal({
  connectedComponent: sendSmsModal,
});

function handleSendSms() {
  sendSmsModalApi.setData({
    name: info.value.name,
    employeeId: info.value.id,
    type: props.type,
    templateList: taskInfo.value?.smsTemplates || [],
  });
  sendSmsModalApi.open();
}

// 发邮件
const [SendEmailModal, sendEmailModalApi] = useVbenModal({
  connectedComponent: sendEmailModal,
});

async function handleSendEmail() {
  const { valid, value: email } = await userFormApi.validateField('email');
  if (!valid) {
    throw new Error('邮箱格式有误');
  }
  console.log('email', email);
  const userFormValues = (await userFormApi.getValues()) as any;
  sendEmailModalApi.setData({
    name: info.value.name,
    employeeId: info.value.id,
    // email: info.value.email,
    email: userFormValues.email,
    type: props.type,
    templateList: taskInfo.value?.emailTemplates || [],
  });
  sendEmailModalApi.open();
}

// 加微信
// 自动加微信

const isCalling = ref(false);

watch(
  () => isCalling.value,
  () => {
    emit('update:calling', isCalling.value);
  },
);

const mainUniqueIdList = ref<string[]>([]);
const mainUniqueIdKey = computed(() => {
  return `call-workbench-${info.value?.id}`;
});

function handleBusy(mainUniqueId: string) {
  console.log('联络面板呼叫通话中，接收mainUniqueId：', mainUniqueId);
  if (mainUniqueId) {
    if (!mainUniqueIdList.value.includes(mainUniqueId)) {
      mainUniqueIdList.value.push(mainUniqueId);
    }
    window.localStorage.setItem(
      mainUniqueIdKey.value,
      JSON.stringify(mainUniqueIdList.value),
    );
  }
}

// 本人历史联络记录列表
const contactHistoryGridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    // trigger: 'row',
  },
  columns: contactHistoryColumns,
  // height: 'auto',
  keepSource: false,
  pagerConfig: {
    enabled: false,
  },
  toolbarConfig: {
    enabled: true,
  },
  proxyConfig: {
    ajax: {
      query: async (_, formValues = {}) => {
        // console.log(formValues);
        const rows = await callLogList({
          taskId: props.taskId,
          employeeId: info.value.id,
          ...formValues,
        });
        return { rows: rows || [] };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'task-contact-history-index',
};

const [ContactHistoryTable] = useVbenVxeGrid({
  gridOptions: contactHistoryGridOptions,
});

const loading = ref(false);
const info = ref<any>({});

// 切换观众时，重新加载信息
watch(
  () => props.audience,
  async (val) => {
    if (val) {
      await handleLoadInfoByClick(val);
    }
  },
);

// 刷新赋值表单
async function refreshContactForm(details: EmployeeVO) {
  // 处理人员标签
  details.labelIds =
    details.labels?.length > 0
      ? details.labels.map((label: any) => label.id)
      : [];

  // 转成地址级联组件接收的数据格式
  addressCodeMapToArray(details, 'addressMap');
  loading.value = false;

  await userFormApi.setValues(details);

  // 编辑场景下，处理带脱敏信息的输入项
  updateSensitiveSchema(
    details,
    [
      ['mobile', 'mobileRequired'],
      ['email', 'email'],
    ],
    userFormApi,
  );
}

// 点击左侧人员列表时，加载观众信息
async function handleLoadInfoByClick(audience: EmployeeVO) {
  console.log('ContactPanel handleLoadInfo', audience);
  contactTabKey.value = '1';
  listTabKey.value = '1';

  loading.value = true;
  const details = await callTaskEmployeeNoDesensitizeInfo(audience.id);
  info.value = details;
  await refreshContactForm(details);
}

// 任务工作台模式，获取联络任务被呼数据
async function handleLoadTaskData() {
  contactTabKey.value = '1';
  listTabKey.value = '1';

  try {
    loading.value = true;
    const details = await callTaskWorkbenchQuery(props.taskId);
    if (details) {
      info.value = details;
      await refreshContactForm(details);
    } else {
      await quit('呼叫任务无数据');
    }
  } catch (error) {
    console.log(error);
    await quit();
  }
}

const taskInfo = ref<any>({});

async function getTaskCallData() {
  if (props.taskId) {
    taskInfo.value = await callTaskInfo(props.taskId);
  }
  // await handleLoadInfoByClick({ id: '1952296624621211649' } as EmployeeVO);
  await handleLoadTaskData();
}

function updateUserFormSchema() {
  userFormApi.updateSchema([
    {
      fieldName: 'name',
      suffix: () => {
        return hasAccessByCodes(['call:employee:register']) ? (
          <Popconfirm onConfirm={autoRegister} title="确认为其自动登记？">
            {info.value?.hasRegister ? (
              ''
            ) : (
              <Button loading={registerLoading.value}>预登记</Button>
            )}
          </Popconfirm>
        ) : (
          ''
        );
      },
    },
    {
      fieldName: 'mobile',
      suffix: () => {
        return (
          <Space>
            <Clink
              employeeId={info.value?.id}
              onBusy={handleBusy}
              phoneNumber={info.value?.mobile}
              size="middle"
              v-model:calling={isCalling.value}
            />
            {hasAccessByCodes(['call:employee:sms']) ? (
              <Button onClick={handleSendSms}>发短信</Button>
            ) : (
              ''
            )}
          </Space>
        );
      },
    },
    {
      fieldName: 'email',
      suffix: () => {
        return hasAccessByCodes(['call:employee:email']) ? (
          <Button onClick={handleSendEmail}>发邮件</Button>
        ) : (
          ''
        );
      },
    },
    // {
    //   fieldName: 'wechatNo',
    //   suffix: () => {
    //     return (
    //       <Space>
    //         <Button>加微信</Button>
    //         <Button>自动加微信</Button>
    //       </Space>
    //     );
    //   },
    // },
  ]);
}

onActivated(() => {
  updateUserFormSchema();
});

onMounted(async () => {
  updateUserFormSchema();
  contactResultFormApi.updateSchema([
    {
      fieldName: 'contactResult',
      componentProps: {
        onChange: (e: any) => {
          console.log(e);
          const contactResultValue = e.target.value;
          contactResultFormApi.setFieldValue('contactDetail', null, false);
          contactResultFormApi.updateSchema([
            {
              fieldName: 'contactDetail',
              componentProps: {
                options: getDictOptions(contactResultValue, true),
              },
            },
          ]);
        },
      },
    },
  ]);
  // 非列表选择的联络任务模式
  if (props.type === 'task') {
    await getTaskCallData();
  }
});

// 退出工作台
const quitLoading = ref(false);

async function quitHandle() {
  quitLoading.value = true;
  // if (info.value.id) {
  //   await callTaskChangeCallStatus({
  //     taskId: props.taskId,
  //     employeeId: info.value.id,
  //     callStatus: 0,
  //   });
  // }
  await quit();
  quitLoading.value = false;
}

async function quit(msg?: string) {
  if (msg) {
    message.warning(msg);
  }
  await closeCurrentTab();
  await router.replace('/contact/task/call');
}

// 提交联络结果
const submitLoading = ref(false);

async function submitContactLog() {
  const { valid: userValid } = await userFormApi.validate();
  const { valid: contactValid } = await contactResultFormApi.validate();
  if (!userValid || !contactValid) {
    message.warning('请先完善必填信息');
    return;
  }
  const userValues = cloneDeep(await userFormApi.getValues());
  userValues.sourceId = info.value.sourceId;

  const contactValues = cloneDeep(await contactResultFormApi.getValues());
  contactValues.taskId = props.taskId;
  contactValues.employeeId = info.value.id;
  if (mainUniqueIdList.value.length > 0) {
    contactValues.mainUniqueId = mainUniqueIdList.value.join(',');
  }
  delete userValues.mobile;
  console.log('人员信息：', userValues);
  console.log('联络结果：', contactValues);

  submitLoading.value = true;
  // 更新人员信息
  await employeeUpdate(userValues, false);

  // 提交联络结果
  await callLogAdd(contactValues as CallLog);
  mainUniqueIdList.value = [];
  window.localStorage.removeItem(mainUniqueIdKey.value);
  submitLoading.value = false;

  // message.warning('模拟提交成功');
  if (props.type === 'task') {
    await refreshTaskData();
  }
}

async function refreshTaskData() {
  await userFormApi.resetForm();
  await contactResultFormApi.resetForm();
  contactResultFormApi.updateSchema([
    { fieldName: 'contactDetail', componentProps: { options: [] } },
  ]);
  await handleLoadTaskData();
}

const { onBeforeRouteLeaveCallPage } = useClinkCall();
onBeforeRouteLeaveCallPage(async () => {
  if (info.value.id && props.type === 'task') {
    await callTaskChangeCallStatus({
      taskId: props.taskId,
      employeeId: info.value.id,
      callStatus: 0,
    });
  }
});
</script>

<template>
  <div class="thin-scrollbar flex flex-1 flex-col overflow-y-auto">
    <Card
      :body-style="{ overflowY: 'auto', height: '100%' }"
      :loading="loading"
      size="small"
      class="p-[10px]"
    >
      <Spin :spinning="loading">
        <Row v-if="info" :gutter="30">
          <Col :span="13">
            <!--<Tabs v-model:active-key="contactTabKey" type="card">-->
            <!--  <TabPane key="1" tab="打电话">-->
            <!--    <UserForm />-->
            <!--  </TabPane>-->
            <!--  <TabPane key="2" tab="发短信">-->
            <!--    <div class="py-5">-->
            <!--      <SmsForm>-->
            <!--        <template #name>{{ info?.name }}</template>-->
            <!--      </SmsForm>-->
            <!--    </div>-->
            <!--  </TabPane>-->
            <!--  <TabPane key="3" tab="发邮件">-->
            <!--    <div class="py-5">-->
            <!--      <EmailForm>-->
            <!--        <template #name>{{ info?.name }}</template>-->
            <!--      </EmailForm>-->
            <!--    </div>-->
            <!--  </TabPane>-->
            <!--</Tabs>-->
            <main-title text="人员信息" />
            <UserForm class="mt-[20px]" />
          </Col>
          <Col :span="11">
            <main-title text="填写联络结果" />
            <ContactResultForm class="mt-[20px]" />
            <div class="mb-[20px] flex justify-end">
              <Space class="flex items-center" size="large">
                <Popconfirm
                  :get-popup-container="getVxePopupContainer"
                  placement="left"
                  title="确定不保存数据直接退出？"
                  @confirm="quitHandle()"
                >
                  <Button
                    v-if="type === 'task'"
                    block
                    size="large"
                    :loading="quitLoading"
                  >
                    退出
                  </Button>
                </Popconfirm>
                <Popconfirm
                  :get-popup-container="getVxePopupContainer"
                  placement="left"
                  title="请检查信息是否无误，确认提交？"
                  @confirm="submitContactLog()"
                >
                  <Button
                    v-access:code="['call:log:add']"
                    block
                    size="large"
                    type="primary"
                    class="!w-[180px]"
                    :loading="submitLoading"
                  >
                    提交
                  </Button>
                </Popconfirm>
              </Space>
            </div>
            <Alert
              message="重要提醒："
              description="离开、关闭或刷新页面会丢失未保存的内容，请确保及时提交。"
              type="warning"
              show-icon
            />
          </Col>
          <Col :span="24">
            <div class="mt-[30px]">
              <Tabs v-model:active-key="listTabKey" type="card">
                <TabPane key="1">
                  <template #tab>
                    <span class="flex items-center gap-1">
                      <VbenIcon
                        class="inline-block"
                        icon="material-symbols:call-log"
                      />历史联系纪录
                    </span>
                  </template>
                  <Spin :spinning="loading">
                    <ContactHistoryTable v-if="info && info.id" />
                  </Spin>
                </TabPane>
                <TabPane key="2">
                  <template #tab>
                    <span class="flex items-center gap-1">
                      <VbenIcon
                        class="inline-block"
                        icon="mdi:shop-look-up"
                      />参观记录
                    </span>
                  </template>
                  <Spin :spinning="loading">
                    <RegisterHistoryTable
                      v-if="info && info.id"
                      :employee-id="info.id"
                    />
                  </Spin>
                </TabPane>
              </Tabs>
            </div>
          </Col>
        </Row>
      </Spin>
    </Card>
    <SendSmsModal />
    <SendEmailModal />
  </div>
</template>

<style scoped lang="scss"></style>
